<!--教职工人员管理-->
<template>
  <div class="avue-crud">
    <basic-container>
      <p class="contain-title">教职工人员管理</p>
      <div class="door-search">
        <p>搜索人员</p>
        <el-input v-model.trim="name" class="search-style" placeholder="请输入姓名" prop="name"></el-input>
        <el-button icon="el-icon-search" type="success" @click="searchPerson()">搜索</el-button>
        <el-button type="warning" @click="resetForm()">重置</el-button>
        <el-button type="danger">批量删除</el-button>
        <el-button type="primary" @click="addItemVisible = true">新增人员</el-button>
      </div>

      <div class="door-search">
        <p>筛选</p>
        <p>性别</p>
        <el-select v-model="sex" class="select-style" placeholder="请选择" prop="sex">
          <el-option
              v-for="item in sexOptions"
              :key="item.sex"
              :label="item.label"
              :value="item.sex">
          </el-option>
        </el-select>
        <p>单位</p>
        <el-select v-model="deptId" class="select-style" placeholder="请选择" prop="deptId">
          <el-option
              v-for="item in deptOptions"
              :key="item.deptId"
              :label="item.label"
              :value="item.deptId">
          </el-option>
        </el-select>
        <p>身份</p>
        <el-select v-model="identity" class="select-style" collapse-tags placeholder="请选择">
          <el-option
              v-for="item in idOptions"
              :key="item.identity"
              :label="item.label"
              :value="item.identity">
          </el-option>
        </el-select>
      </div>
      <br>
      <el-button type="success" @click="setItemVisible = true">批量导入</el-button>
      <el-button type="success" @click="exportItemVisible()">报表导出</el-button>
      <el-button type="success">导入模板下载</el-button>
      <br>
      <br>
      <!--    门禁组列表-->
      <el-form>
        <el-form-item>
          <el-table ref="multipleTable" :data="teacherData"
                    style="width: 100%"
                    tooltip-effect="dark"
                    @selection-change="handleSelectionChange">
            <el-table-column label="全选"
                             type="selection"
                             width="55">
            </el-table-column>
            <!--            <el-table-column label="人员id" prop="id"></el-table-column>-->
            <el-table-column label="姓名" prop="name"></el-table-column>
            <el-table-column label="工号" prop="number"></el-table-column>
            <el-table-column :formatter="tableSex" label="性别" prop="sex">
            </el-table-column>
            <el-table-column label="单位" prop="deptName"></el-table-column>
            <el-table-column label="手机号" prop="phone"></el-table-column>
            <el-table-column label="人脸照片" prop="photoId">
              <!--              <template slot-scope="scope">-->
              <!--                <el-popover placement="right" title="" trigger="hover">-->
              <!--                  <img :src="scope.row.filepath"  style="height: 200px;width: 200px"/>-->
              <!--                  <img slot="reference" :src="scope.row.filepath" :alt="scope.row.filepath" style="height: 40px;width: 40px">-->
              <!--                </el-popover>-->
              <!--              </template>-->
              <template slot-scope="scope">
                <p v-if="scope.row.photoId === null">未上传</p>
                <el-button v-else type="warning" @click="onPreview(scope.row)">查看大图</el-button>
              </template>

              <el-image-viewer
                  v-if="showViewer"
                  :on-close="closeViewer"
                  :preview-src-list="srcList"
                  :url-list="[url]"/>
            </el-table-column>
            <el-table-column label="可通行门禁" prop="groupName"></el-table-column>
            <el-table-column label="身份" prop="identityName"></el-table-column>
            <el-table-column label="人员修改时间" prop="updateTime"></el-table-column>
            <el-table-column label="修改操作人" prop="operator"></el-table-column>
            <el-table-column label="操作" prop="opera" width="142px">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    type="primary"
                    @click="handleEdit(scope.row)">编辑
                </el-button>
                <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <el-pagination
          :data="teacherData"
          :total="total"
          background layout="prev, pager, next"
          style="text-align: center" @current-change="handleCurrentChange">
      </el-pagination>
    </basic-container>

    <!--    新增人员弹窗-->
    <el-dialog
        :visible.sync="addItemVisible"
        center
        title="新增人员"
        width="40%" @close="dictItemVisible">
      <div class="upload-photo">
        <el-form>
          <el-upload
              ref="upload"
              :auto-upload="false"
              :headers="headers"
              :on-success="handleAvatarSuccess"
              :show-file-list="true"
              accept="image/png,image/gif,image/jpg,image/jpeg"
              action="/campus/persons/photo"
              class="avatar-uploader">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-form-item>
            <el-button size="small" type="primary" @click="uploadFile">立即上传</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="people-info">
        <div class="door-search">
          <p>姓名</p>
          <el-input v-model="name" class="people-style" placeholder="请输入姓名" prop="name"></el-input>
        </div>
        <div class="door-search">
          <p>工号</p>
          <el-input v-model="number" class="people-style" placeholder="请输入工号"></el-input>
        </div>
        <div class="door-search">
          <p>单位</p>
          <el-select v-model="deptId" class="people-style" placeholder="请选择">
            <el-option
                v-for="item in deptOptions"
                :key="item.deptId"
                :label="item.label"
                :value="item.deptId">
            </el-option>
          </el-select>
        </div>
        <div class="door-search">
          <p>身份</p>
          <el-select v-model="identity" class="people-style" placeholder="请选择">
            <el-option
                v-for="item in idOptions"
                :key="item.identity"
                :label="item.label"
                :value="item.identity">
            </el-option>
          </el-select>
        </div>
        <div class="door-search">
          <p>性别</p>
          <el-select v-model="sex" class="people-style" placeholder="请选择" prop="sex">
            <el-option
                v-for="item in sexOptions"
                :key="item.sex"
                :label="item.label"
                :value="item.sex">
            </el-option>
          </el-select>
        </div>
        <div class="door-search">
          <p>手机号</p>
          <el-input v-model="phone" class="people-style" placeholder="请输入手机号" prop="phone"></el-input>
        </div>
        <div class="door-search">
          <p>可通行门禁</p>
          <el-select v-model="accessGroupId" class="people-style" placeholder="请选择">
            <el-option
                v-for="item in accOptions"
                :key="item.accessGroupId"
                :label="item.label"
                :value="item.accessGroupId">
            </el-option>
          </el-select>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addItemVisible = false">取消</el-button>
        <el-button @click="addSaveItemVisible()">保存</el-button>
      </div>
    </el-dialog>

    <!--    编辑人员弹窗-->
    <el-dialog
        :visible.sync="dialogEditVisible"
        center
        title="编辑人员"
        width="40%" @close="dictItemVisible">
      <div class="upload-photo">
        <el-form>
          <el-upload
              ref="upload"
              :auto-upload="false"
              :headers="headers"
              :on-success="handleAvatarSuccess"
              :show-file-list="true"
              accept="image/png,image/gif,image/jpg,image/jpeg"
              action="/campus/persons/photo"
              class="avatar-uploader">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-form-item>
            <el-button size="small" type="primary" @click="uploadFile">立即上传</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="people-info">
        <div class="door-search">
          <p>姓名</p>
          <el-input v-model="name" class="people-style" placeholder="" prop="name"></el-input>
        </div>
        <div class="door-search">
          <p>工号</p>
          <el-input v-model="number" class="people-style" placeholder="请输入" prop="number"></el-input>
        </div>
        <div class="door-search">
          <p>单位</p>
          <el-select v-model="deptId" class="people-style" placeholder="请选择" prop="deptId">
            <el-option
                v-for="item in deptOptions"
                :key="parseInt(item.deptId)"
                :label="item.label"
                :value="parseInt(item.deptId)">
            </el-option>
          </el-select>
        </div>
        <div class="door-search">
          <p>身份</p>
          <el-select v-model="identity" class="people-style" placeholder="请选择" prop="identity">
            <el-option
                v-for="item in idOptions"
                :key="parseInt(item.identity)"
                :label="item.label"
                :value="parseInt(item.identity)">
            </el-option>
          </el-select>
        </div>
        <div class="door-search">
          <p>性别</p>
          <el-select v-model="sex" class="people-style" placeholder="请选择" prop="sex">
            <el-option
                v-for="item in sexOptions"
                :key="parseInt(item.sex)"
                :label="item.label"
                :value="parseInt(item.sex)">
            </el-option>
          </el-select>
        </div>
        <div class="door-search">
          <p>手机号</p>
          <el-input v-model="phone" class="people-style" placeholder="请输入" prop="phone"></el-input>
        </div>
        <div class="door-search">
          <p>可通行门禁</p>
          <el-select v-model="accessGroupId" class="people-style" placeholder="请选择" prop="accessGroupId">
            <el-option
                v-for="item in accOptions"
                :key="parseInt(item.accessGroupId)"
                :label="item.label"
                :value="parseInt(item.accessGroupId)">
            </el-option>
          </el-select>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditVisible = false">取消</el-button>
        <el-button @click="editSaveItemVisible()">保存</el-button>
      </div>
    </el-dialog>

    <!--    导入模板弹窗-->
    <el-dialog
        :visible.sync="setItemVisible"
        center
        width="40%" @close="dictItemVisible">
      <el-form :model="form">
        <el-form-item>
          <p style="font-weight: bold">导入模板</p>
          <el-upload
              ref="upload"
              :auto-upload="false"
              :before-upload="beforeUploadFile"
              :file-list="fileList"
              :http-request="handleupload"
              :limit=limitNum
              :on-change="handleChange"
              :on-exceed="exceedFile"
              accept=".xlsx"
              action="">
            <el-button slot="trigger" type="success">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="uploadItemVisible()">上传</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>

<script>
import {addPerson, delStudent, editPerson, personList, searchPerson, showPersonPhoto} from '@/api/people/person'
import {SearchObj} from '@/api/depart/department'
import {identityObj} from '@/api/depart/identity'
import {doorList} from '@/api/door/access'
import ElImageViewer from 'element-ui/packages/image/src/image-viewer'
import store from "@/store";

export default {
  name: "teacher",
  components: {ElImageViewer},
  data() {
    return {
      filepath: '',
      input: '',
      sex: '',
      name: '',
      number: '',
      phone: '',
      total: null,
      loading: true,         // 遮罩层
      deptId: '',
      deptOptions: [{
        deptId: '',
        label: ''
      }],
      options: [],
      sexOptions: [{         //性别选择的下拉框
        sex: '1',
        label: "男"
      }, {
        sex: '0',
        label: "女"
      }],
      identity: '',
      idOptions: [{}],
      accessGroupId: '',
      accOptions: [{}],
      value: [],
      states: [],
      selects: [{          //多选下拉框
        value: ''
      }, {
        value: '',
      },],
      teacherData: [],
      editData: [],
      imageUrl: '',    //照片上传
      addItemVisible: false,          //新增人员弹窗
      dialogDelVisible: false,        //删除人员弹窗
      // dictItemVisible:false,        // 通用的弹窗的关闭事件
      dialogEditVisible: false,      // 编辑人员弹窗
      setItemVisible: false,         // 导入模板弹窗的显示和隐藏
      limitNum: 1,
      fileList: [],
      form: {
        file: ''
      },
      //上传头像
      hideUpload: true,
      // dialogVisible: false,//图片预览弹窗
      limitPho: 1,
      showViewer: false, // 显示查看器
      url: '',
      srcList: [''],
      headers: {
        Authorization: "Bearer " + store.getters.access_token,
      },
    }
  },
  mounted() {
    this.showPersonList();
    this.searchOptions();
  },
  methods: {
    //展示人员表格信息
    showPersonList: function () {
      let param = {
        'id': '',
        'size': '',
        'pageCurrent': this.currentPage,
      }
      this.loading = true;
      // debugger
      personList(param).then(res => {
        if (res.data.code === 0) {
          this.total = res.data.data.rowCount;
          // let list=res.data.data.records;
          // let teacherList=[]
          // for(var i in list){
          //   teacherList.push(list[i]);
          // }
          // this.teacherData = teacherList
          this.teacherData = res.data.data.records;
          this.loading = false;
          console.log(this.teacherData)
        }
      });
    },
    tableSex: function (row, column, cellValue) {
      if (cellValue == '0') {
        return '女';
      } else if (cellValue == '1') {
        return '男';
      }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      console.log(this.currentPage)
      this.showPersonList();
    },
    //查找人员
    searchPerson() {
      let param = {
        "name": this.name,
        "sex": this.sex,
        "deptId": this.deptId,
        "identity": this.identity,
        // 'current': this.currentPage,
      }
      // debugger
      personList(param).then(res => {
        if (res.data.code === 0) {
          this.total = res.data.data.rowCount;
          this.teacherData = res.data.data.records;
          console.log(this.teacherData)
        }
      });
    },
    searchOptions() {
      //获取所有单位数据
      SearchObj().then(res => {
        if (res.data.code === 0) {
          this.deptData = res.data.data.records;
          this.deptOptions = this.deptData.map(item => {
            return {deptId: `${item.deptId}`, label: `${item.name}`};
          })
          // let deptOptions=[];
          // this.deptData.map((item) => {
          //   deptOptions.push({ label: item.name , deptId:item.deptId});
          // });
          console.log(this.deptOptions)  //所有的deptId和name
        }
      });
      //获取所有的身份数据
      identityObj().then(res => {
        if (res.data.code === 0) {
          this.idData = res.data.data.records;
          this.idOptions = this.idData.map(item => {
            return {identity: `${item.id}`, label: `${item.name}`};
          })
          console.log(this.idOptions)  //所有的deptId和name
        }
      });
      //获取可选门禁组数据
      doorList().then(res => {
        if (res.data.code === 0) {
          this.accessData = res.data.data.records;
          this.accOptions = this.accessData.map(item => {
            return {accessGroupId: `${item.id}`, label: `${item.groupName}`};
          })
          console.log(this.accOptions)  //所有的deptId和name
        }
      });

    },
    //表格中的图片查看
    onPreview(row) {
      // debugger
      showPersonPhoto(row.photoId).then(res => {
        if (res.data.code === 0) {
          window.open(res.data.data)
        }
      });
      this.showViewer = true

    },
    // 关闭查看器
    closeViewer() {
      this.showViewer = false
    },

    // 重置
    resetForm: function () {
      this.name = null;
      this.sex = null;
      this.deptId = null;
      this.identity = null;
      this.showPersonList();
    },
    //关闭弹窗清空内容
    dictItemVisible: function () {
      this.input = null;
      this.name = null;
      this.sex = null;
      this.number = null;
      this.imageUrl = null;
      this.deptId = null;
      this.phone = null;
      this.accessGroupId = null;
      this.identity = null;
    },
    //批量上传
    // 文件超出个数限制时的钩子
    exceedFile(files, fileList) {
      this.$notify.warning({
        title: '警告',
        message: `只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`
      });
    },
    // 文件状态改变时的钩子
    handleChange(file, fileList) {
      console.log('change')
      console.log(file)
      this.form.file = file.raw
      console.log(this.form.file)
      console.log(fileList)
    },
    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      console.log('before upload')
      console.log(file)
      let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      let size = file.size / 1024 / 1024
      if (extension !== 'xlsx') {
        this.$notify.warning({
          title: '警告',
          message: `只能上传Excel2017（即后缀是.xlsx）的文件`
        });
      }
      if (size > 10) {
        this.$notify.warning({
          title: '警告',
          message: `文件大小不得超过10M`
        });
      }
    },
    handleupload() {
      const data = new FormData()
      const fileUps = this.form.file
      data.append('file', fileUps)
      this.$axios({
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        url: '/campus/persons/excel_Import',
        data: data,
        method: 'post'
      }).then(res => {
        if (res.data === "success") {
          this.$message.success('文件上传成功')
          console.log(this.$message)
        } else {
          this.$message.error('文件上传失败')
        }
      })
      // }
    },
    uploadItemVisible() {
      // debugger
      if (this.$refs.upload.uploadFiles.length < 1) {
        this.$message.warning('请上传文件')
        console.log(this.$refs.upload.uploadFiles)
      } else {
        this.$refs.upload.submit()

      }
    },
    // TODO 报表导出
    // exportItemVisible(){
    //  let url='/campus/persons/excel_export';
    // let param= '?filename=teacher.elsx';
    // window.open(`${url}`);
    // },
    exportItemVisible() {
      axios({
        method: 'get',
        url: '/campus/persons/excel_export',
        headers: {
          key: ''
        },
        responseType: "blob"
      })
          .then(res => {
            if (res.data.type) {
              // 文件下载
              const blob = new Blob([res.data], {
                type: "application/vnd.ms-excel"
              });
              let link = document.createElement('a');
              link.href = URL.createObjectURL(blob);
              link.setAttribute('download', '导出文件.xlsx');
              link.click();
              link = null;
              this.$message.success('导出成功');
            } else {
              // 返回json
              this.$message.warning(res.data.msg);
            }
          })
          .catch(err => {
            this.$message.error("下载失败");
          });
    },
    // deleteRowElection () {
    //   // this.$refs.inputFormRef.resetFields()
    // },
    deleteRowElection(index) {
      this.input.splice(index, 1);
    },
    //表格的全选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    //新增人员弹窗
    addSaveItemVisible: function () {
      let param = {
        "name": this.name,
        "sex": this.sex,
        "number": this.number,
        "phone": this.phone,
        "identityId": '',
        "nation": "",
        "password": "",
        "photoId": this.photoId,
        "deptId": this.deptId,
        "identity": this.identity,
        "accessGroupId": this.accessGroupId,
      }
      // console.log(param)
      if (this.name == "" || this.sex == "") {
        this.$message.warning("姓名或者性别不能为空！");
      } else {
        addPerson(param).then(res => {
          console.log(param)
          if (res.data.code === 0) {
            this.addItemVisible = false;
            this.teacherData = res.data.data.records;
            this.showPersonList(this.page)
            this.$message.success('添加成功')
          }
        });
      }
    },
    //编辑人员
    handleEdit(row) {
      this.dialogEditVisible = true;
      //点击编辑按钮 调用id查询接口展示该人员的信息
      searchPerson(row.id).then(res => {
        if (res.data.code === 0) {
          let list = res.data.data;
          //反参为对象 两种方式
          //将反参的对象转换为数组，再取第一组下的值
          let editList = []
          editList.push(list)
          this.editData = editList
          this.name = this.editData[0].name;
          this.sex = this.editData[0].sex;
          this.id = this.editData[0].id;
          this.number = this.editData[0].number;
          this.phone = this.editData[0].phone;
          this.identity = this.editData[0].identity;
          this.deptId = this.editData[0].deptId;
          this.accessGroupId = this.editData[0].accessGroupId;
          this.photoId = this.editData[0].photoId;
          //直接取反参的对象取值
          // this.name=list.name;
          // this.sex=list.sex;
          console.log(this.editData)
        }
      });
    },
    editSaveItemVisible: function () {
      //获取所选人员
      let param = {
        "id": this.id,
        "name": this.name,
        "sex": this.sex,
        "number": this.number,
        "phone": this.phone,
        "identityId": "",
        "nation": "",
        "password": "123456",
        "photoId": this.photoId,
        "deptId": this.deptId,
        "identity": this.identity,
        "accessGroupId": this.accessGroupId,
      }
      // debugger
      editPerson(param).then(res => {
        if (res.data.code === 0) {
          this.teacherData = res.data.data.records;
          this.showPersonList(this.page)
          this.$message.success('修改成功')
          this.dialogEditVisible = false
        }
      });
    },
    //删除人员
    handleDelete: function (row) {
      this.$confirm('是否确认删除人员？删除后人员相关通行权限即将被删除，请谨慎操作', '提示', {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delStudent(row.id)
      }).then(data => {
        this.$message.success('删除成功')
        this.showPersonList(this.page)
      }).catch(() => {

      })
    },
    //上传头像
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.photoId = res.data;
    },
    //头像上传之前的钩子
    // handleBeforeUpload(file) {
    //   if (!(file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
    //     this.$notify.warning({
    //       title: '警告',
    //       message: '请上传格式为image/png, image/gif, image/jpg, image/jpeg的图片'
    //     })
    //   }
    //   let size = file.size / 1024 / 1024 / 2
    //   if (size > 2) {
    //     this.$notify.warning({
    //       title: '警告',
    //       message: '图片大小必须小于2M'
    //     })
    //   }
    //   // debugger
    //   let data = new FormData();//通过form数据格式来传
    //   data.append("file", file); //传文件
    //   console.log(data.get('file'));
    //   this.axios({
    //     url: "/campus/persons/photo",
    //     method: "post",
    //     data: data,
    //     headers: {
    //       'Content-Type': 'multipart/form-data'
    //     }
    //   }).then(res => {
    //     if (res.data.code === 0) {
    //       this.$message.success('照片上传成功')
    //       this.photoId = res.data.data
    //       console.log(this.photoId)
    //       console.log(this.$message)
    //     } else {
    //       this.$message.error('照片上传失败')
    //     }
    //   })
    // },
    // 文件列表移除文件时的钩子
    handleRemove(file, fileList) {
      this.hideUpload = fileList.length >= this.limitPho;
    },
    uploadFile() {
      this.$refs.upload.submit()

    },
    // imgChange (files, fileList) {
    //   this.hideUpload = fileList.length >= this.limitPho;
    //   if (fileList) {
    //     this.$refs.uploadElement.clearValidate();
    //   }
    // },
    // tocancel () {
    //   this.dialogVisible2 = false
    // }
    //分页改变当前数据
    // handleSizeChange(val){
    //   this.size = val;
    //   console.log(this.currentPage)
    //   this.showPersonList();
    // },

  },

}
</script>

<style scoped>
.contain-title {
  font-weight: bold;
}

.door-search p {
  font-size: 14px;
  display: inline-block;
  margin-right: 20px;
}

.search-style {
  width: 15%;
  margin-right: 20px;
}

.select-style {
  width: 15% !important;
  margin-right: 20px;
}

/*头像上传*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.upload-photo {
  margin-left: 50px;
  display: inline-block;
  float: left;
}

.people-info {
  margin-left: 70px;
  display: inline-block;
}

.people-style {
  width: 70% !important;
  display: inline-block;
  float: right;
}

.import-style {
  width: 60%;
  margin-right: 20px;
}
</style>
